package com.googlecode.cnasort.cc.rmi.client.core;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.googlecode.cnasort.cc.rmi.common.data.RMIDirectory;
import com.googlecode.cnasort.cc.rmi.common.data.RMIFile;
import com.googlecode.cnasort.cc.rmi.common.data.impl.RMIDirectoryImpl;

public class FileLoaderClientDownload
{
    private FileLoaderClientCoreImpl clientCore;
    private String                   prefixToDownload;

    public FileLoaderClientDownload(
        final FileLoaderClientCoreImpl clientCore,
        final String                   prefixToDownload
        )
    {
        this.clientCore       = clientCore;
        this.prefixToDownload = prefixToDownload;
    }

    public void doDownload() throws IOException
    {
        doDownload( new RMIDirectoryImpl( new File( prefixToDownload ) ) );
    }

    private void doDownload( RMIDirectory...folders ) throws IOException
    {
        for( RMIDirectory folder : folders ) {
            RMIDirectory[] subFolders = this.clientCore.getDirectories( folder );

            doDownload( subFolders );

            RMIFile[] files = this.clientCore.getFiles( folder );

            for( RMIFile file : files ) {
                doDownload( file );
                }
            }
    }

    private void doDownload( RMIFile file ) throws IOException
    {
        System.out.println( "getting: " + file.getFile() );

        String name       = file.getFile().getPath().substring( prefixToDownload.length() );
        File   outputFile = new File( this.clientCore.getOutputDirFile(), name );
        File   parentFile = outputFile.getParentFile();

        if( ! parentFile.exists() ) {
            parentFile.mkdirs();
            }

        System.out.println( "writing: " + outputFile + " * " + parentFile );

        OutputStream os = new BufferedOutputStream( new FileOutputStream ( outputFile ) );

        try {
        	this.clientCore.openFileTransfert( file );

            while( ! this.clientCore.isFileTransfertComplete() ) {
                os.write( this.clientCore.nextFileTransfertPart() );
                }

            this.clientCore.closeFileTransfert();
            }
        finally {
            os.close();
            }
    }
}
